const api = require('../../utils/backendAPI.js');
var expdt = {
  1011:[], 
  1021:[],
  1022:[],
  1031:[],
  1041:[],
  1042:[],
  1051:[],
  1061:[],
  1062:[],
  1071:[],
  1081:[],
  1082:[],
  1091:[]
}

var dtindex = {
  1011:0, 
  1021:0,
  1022:0, 
  1031:0, 
  1041:0, 
  1042:0, 
  1051:0, 
  1061:0, 
  1062:0, 
  1071:0, 
  1081:0,
  1082:0,
  1091:0
}

function isEmpty(v) {
  //legacy for 1011 1021 1022 whose json has no attr 'v'
  if (v == undefined) {
    return false
  }
  var flag = true;
  for (i = 0; i < v.length; i++) {
    if (v[i] != "") {
      flag = false
    }
  }
  return flag
}

function hasIllegalCharacter(v) {
  if (v == undefined) {
    return false
  }
  var legal = ["1","2","3","4","5","6","7","8","9","0",".","-","/","e"," ","+","-"]
  for (i = 0; i < v.length; i++) {
    for (j = 0; j < v[i].length; j++) {
      if (!legal.includes(v[i][j])) {
        console.log("illegal character: " + v[i][j])
        return true
      }
    }
    
  }
  return false
}

module.exports.pushToServer = function(index,e) {
    var json = JSON.parse(e)
    console.log("json.v: " + json.v)
    

    if (isEmpty(json.v)) {
      console.log("empty data")
      wx.showToast({
        icon: 'none',
        title: '数据为空，请填写数据'
      })
    }

    else if (hasIllegalCharacter(json.v)) {
      console.log("illegal data")
      wx.showToast({
        icon: 'none',
        title: '含有非法字符'
      })
    }

    else {
      api.uploadExpData({
          experiment: index, 
          data: e
        }).then(res => {
          console.log("upload to " + index)
          //上传或覆盖成功
          wx.showToast({
            title: '上传成功'
          })
        })
    }
}

function process(dt) {
  console.log(dt)
  newdt = []
  for (i=0; i<dt.length; i++) {
    if (JSON.parse(dt[i]).v != undefined) {
      newdt.push(dt[i])
    }
  }
  return Array.from(new Set(newdt))
}

module.exports.fetchFromServer = async function(index) {
    if (dtindex[index] == 0) {
      expdt[index] = process((await api.getExpData({
        experiment: index
      })).data.oid)
    }
    if (expdt[index].length == 0) {
      wx.showToast({
        icon: 'none',
        title: '本实验暂无数据'
      })
      return ""
    }
    var dt = expdt[index]
    console.log(dt)
    var item = JSON.parse(dt[dtindex[index]])
    length = dt.length
    console.log("length: " + length)
    idx = dtindex[index] + 1
    console.log("index: " + idx)

    wx.showToast({
      icon: 'none',
      title: '第' + idx + "/" +  length + '组数据'
    })
    dtindex[index]++
    if (dtindex[index] == expdt[index].length) {
      // wx.showToast({
      //   icon: 'none',
      //   title: '已是最后一组，再次点击则回到第一组'
      // })
      dtindex[index] = 0
    }
    return item
}